package br.com.jbssistemas.dirfweb.filter;

import br.com.jbssistemas.dirfweb.entidades.Administrador;
import br.com.jbssistemas.dirfweb.entidades.Beneficiario;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * Renato Machado
 */
@WebFilter(filterName = "AuthFilter", urlPatterns = {"/*"})
public class AuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest rq = (HttpServletRequest) request;

        HttpServletResponse rp = (HttpServletResponse) response;

        Object object = rq.getSession().getAttribute("acesso");

        Beneficiario beneficiario = null;
        Administrador administrador = null;

        if (object != null) {

            beneficiario = ((Beneficiario) object);
            administrador = ((Administrador) object);

        }

        String url = rq.getRequestURL().toString();

        if (beneficiario == null && administrador == null) {

            if (url.contains("administracao") || url.endsWith("dirf")
                    || url.endsWith("upload")) {

                rp.sendRedirect("../index.xhtml");

            } 

        }

        try {

            chain.doFilter(request, response);

        } catch (Throwable t) {

            System.err.println(t);

        }

    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

}
